//
//  MTTaskUserHeaderView.swift
//  MT
//
//  Created by ooops on 2020/5/30.
//  Copyright © 2020 张强. All rights reserved.
//

import UIKit
import MTCategory

protocol MTTaskUserHeaderViewDelegate: NSObjectProtocol {
    
    /// 聚会任务群顶部横幅按钮操作
    /// - Parameters:
    ///   - sender: view
    ///   - userType: 用户角色类型 MTPartyGroupTaskUserType
    ///   - actionStatus: 对应角色下的活动状态
    func didClickActionButton(sender: MTTaskUserHeaderView, userType: MTPartyGroupTaskUserType, actionStatus: MTPartyGroupTaskStatusType, canSign: Bool)
}

class MTTaskUserHeaderView: UIView {
    
    weak var delegate: MTTaskUserHeaderViewDelegate?
    /// 是否可以签到 - 签到时间为 活动开始的24小时内
    private var canSign: Bool = false
    
    fileprivate lazy var taskProvider: MTProvider<MTCreateTaskAPI> = {
        return MTProvider<MTCreateTaskAPI>(plugins: [])
    }()
    
    fileprivate let countDownTimer = WMCountDown()
    
    private func timestampServerCheck() {
        MTCreateTaskTool.timastamp(provider: taskProvider, complete: { [weak self] (model) in
            guard let weakSelf = self else { return }
            if let m = model, m.code == 200, let timestamp = m.timestamp {
                if weakSelf.subModel?.status == .started, weakSelf.subModel?.type != .ownner {
                    weakSelf.reloadButtonTitle(timestamp)
                } else {
                    if weakSelf.subModel?.type == .ownner {
                        if let t = weakSelf.subModel?.startTime {
                            if let data = DateManager.date(dateString: t, format: "yyyy-MM-dd HH:mm") {
                                let ds = DateManager.string(date: data, format: "yyyy年MM月dd日 HH:mm")
                                weakSelf.countTimeLabel.text = ds
                            }
                        }
                    } else {
                        weakSelf.reloadButtonTitle(timestamp)
                    }
                }
            }
        }) { [weak self] (_) in
            guard let weakSelf = self else { return }
            weakSelf.countTimeLabel.text = ""
        }
    }
    
    private func reloadButtonTitle(_ timestamp: TimeInterval) {
        if let t = subModel?.startTime {
            if let data = DateManager.date(dateString: t, format: "yyyy-MM-dd HH:mm") {
                let ds = DateManager.string(date: data, format: "yyyy年MM月dd日 HH:mm")
                countTimeLabel.text = ds
            }
        }
        let currentTime = DateManager.dateString(timeInterval: timestamp / 1000, format: "yyyy-MM-dd HH:mm")
        self.countDownTimer.countDown = { [weak self] (d, h, m, s) in
            guard let weakSelf = self else { return }
            if let day = Int(d),  day < 1 {
                weakSelf.canSign = true
                let time = "倒计时: \(d)天\(h)小时\(m)分"
                weakSelf.countTimeLabel.text = time
            }
            
            DispatchQueue.main.async {
                switch weakSelf.subModel?.type {
                    case .sign:
                        weakSelf.signButton.setTitle("已签到", for: .normal)
                        weakSelf.signButton.backgroundColor = UIColor(hex: 0xffe9a6)
                    default:
                        weakSelf.signButton.setTitle(weakSelf.canSign ? "点击签到" : "查看详情", for: .normal)
                        weakSelf.signButton.backgroundColor = UIColor(hex: 0xffc000)
                }
            }
        }
        // 开始倒计时
        // 可以传递开始时间参数，用于计算倒计时时间差，不传，默认从系统当前时间开始计算时间差
        if let et = self.subModel?.startTime {
            self.countDownTimer.start(with: currentTime, end: et)
        }
    }
    
    /// 刷新视图状态
    func reload() {
        timestampServerCheck()
        
        partyStatusLabel.text = subModel?.status == .wating ? "聚会等待开始" : subModel?.status == .started ? "聚会已开始" : "聚会已结束"
        switch subModel?.type {
        case .ownner:
            self.signButton.isHidden = true
            self.ownnerButton.isHidden = false
            switch subModel?.status {
            case .started:
                self.ownnerButton.setTitle("发送红包", for: .normal)
                self.ownnerButton.isHidden = false
            case .wating:
                self.ownnerButton.isHidden = true
            default:
                //self.ownnerButton.setTitle("发送红包", for: .normal)
                self.ownnerButton.isHidden = true
                break
            }
        case .sendPack:
            self.ownnerButton.setTitle("结束聚会", for: .normal)
        default:
            self.signButton.isHidden = false
            self.ownnerButton.isHidden = true
//            switch subModel?.type {
//            case .sign:
//                self.signButton.setTitle("已签到", for: .normal)
//                self.signButton.backgroundColor = UIColor(hex: 0xffe9a6)
//            default:
//                self.signButton.setTitle(canSign ? "点击签到" : "查看详情", for: .normal)
//                self.signButton.backgroundColor = UIColor(hex: 0xffc000)
//            }
        }
        
//        switch model?.status {
//        case .wating:
//            partyStatusLabel.text = "聚会等待开始"
//            self.ownnerButton.isHidden = true
//            self.signButton.isHidden = true
//            self.countTimeLabel.text = model?.startTime
//        case .started:
//            partyStatusLabel.text = "聚会已开始"
//
//            self.ownnerButton.isHidden = model?.type != .ownner
//            self.signButton.isHidden = model?.type == .ownner
//        case .ended:
//            self.ownnerButton.isHidden = true
//            self.signButton.isHidden = true
//        default:
//            self.ownnerButton.isHidden = false
//            self.signButton.isHidden = true
//        }
    }
    
    var model: MTTaskStatusInfoModel? {
        didSet {
            self.subModel = model?.result
        }
    }
    
    private var subModel: MTTaskStatusInfoSubModel? {
        didSet {
            reload()
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
        makeConstraint()
    }
    
    private func setupUI() {
        addSubview(bgImageView)
        bgImageView.addSubview(partyStatusLabel)
        bgImageView.addSubview(lineView)
        bgImageView.addSubview(countTimeLabel)
        bgImageView.addSubview(signButton)
        bgImageView.addSubview(ownnerButton)
    }
    
    private func makeConstraint() {
        bgImageView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        partyStatusLabel.snp.makeConstraints { (make) in
            make.left.top.equalToSuperview().offset(20)
        }
        
        lineView.snp.makeConstraints { (make) in
            make.left.equalTo(partyStatusLabel)
            make.top.equalTo(partyStatusLabel.snp.bottom).offset(4)
            make.width.equalTo(60)
            make.height.equalTo(3)
        }
        
        countTimeLabel.snp.makeConstraints { (make) in
            make.left.equalTo(lineView)
            make.top.equalTo(lineView.snp.bottom).offset(5)
        }
        
        signButton.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
            make.size.equalTo(CGSize(width: 80, height: 30))
        }
        
        ownnerButton.snp.makeConstraints { (make) in
            make.centerY.equalToSuperview()
            make.right.equalToSuperview().offset(-20)
            make.size.equalTo(CGSize(width: 80, height: 30))
        }
    }
    
    lazy var bgImageView: UIImageView = {
        let imageV = UIImageView()
        imageV.layer.masksToBounds = true
        imageV.isUserInteractionEnabled = true
        imageV.image = UIImage(named: "bg_party_status_bg")
        return imageV
    }()
    
    lazy var partyStatusLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(16)
        l.textColor = UIColor.white
        l.text = "聚会等待开始"
        return l
    }()
    
    lazy var lineView: UIView = {
        let v = UIView()
        v.backgroundColor = UIColor(hex: 0xffc000)
        return v
    }()
    
    lazy var countTimeLabel: UILabel = {
        let l = UILabel()
        l.font = PingFangSCSemiboldFont(12)
        l.textColor = .white
        //l.text = "倒计时: 12天xxx小时"
        return l
    }()
    
    lazy var signButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("点击签到", for: .normal)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(14)
        btn.backgroundColor = UIColor(hex: 0xffc000)
        btn.addTarget(self, action: #selector(MTTaskUserHeaderView.sign(sender:)), for: .touchUpInside)
        btn.layer.cornerRadius = 15
        btn.layer.masksToBounds = true
        return btn
    }()
    
    lazy var ownnerButton: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setTitle("", for: .normal)
        btn.addTarget(self, action: #selector(MTTaskUserHeaderView.ownner(sender:)), for: .touchUpInside)
        btn.setTitleColor(UIColor.text.x1d1a1a, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(14)
        btn.backgroundColor = UIColor(hex: 0xffc000)
        btn.layer.cornerRadius = 15
        btn.layer.masksToBounds = true
        return btn
    }()
    
    @objc private func sign(sender: UIButton) {
        guard let m = subModel else { return }
        self.delegate?.didClickActionButton(sender: self, userType: m.type!, actionStatus: m.status!, canSign: self.canSign)
    }
    
    @objc private func ownner(sender: UIButton) {
        guard let m = subModel else { return }
        self.delegate?.didClickActionButton(sender: self, userType: m.type!, actionStatus: m.status!, canSign: false)
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
    }


}
